import axios from 'axios'
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useTokenStore } from "@/stores/token";
const service = axios.create({
    baseURL: 'http://localhost:8080'
});
//Axios的请求的拦截器
service.interceptors.request.use(function (config) {
    const tokenStore = useTokenStore();
    if (!config.url.startsWith("/login")) {
        //如果不是登录请求就要在请求头中添加token
        config.headers.token = tokenStore.tokenStr;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
//响应拦截器
service.interceptors.response.use(resp => {
    const tokenStore = useTokenStore();
    //获取续期的jwt
    let token = resp.headers.token;
    tokenStore.update(token);
    return resp.data;
}, error => {
    if (error.status == 403) {
        ElMessage.error({
            message: '令牌错误，请重新登陆',
            duration: 1200,
            onClose: () => {//提示信息消失时的回调
                //删除sessionStorage
                const tokenStore = useTokenStore();
                tokenStore.$reset();
                //跳转到后台首页
                router.push('/login');
            }
        });
    }
});
export default service;